package com.xinzhi.handler;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinzhi.anno.CheckRole;
import com.xinzhi.domain.Role;
import com.xinzhi.domain.User;
import com.xinzhi.domain.UserRole;
import com.xinzhi.domain.dto.UserDto;
import com.xinzhi.service.LoginService;
import com.xinzhi.service.RoleService;
import com.xinzhi.service.UserRoleService;
import com.xinzhi.utils.Result;
import com.xinzhi.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

@Component
//@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;
    @Autowired private UserRoleService userRoleService;
    @Autowired private RoleService roleService;
    public static ThreadLocal<UserDto> userLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在执行controller方法(Handler)之前进行执行
        if (!(handler instanceof HandlerMethod)){
            //Handler 可能是资源handler 可能是RequestResourceHandler  springboot访问静态资源默认去class path 下的static目录去查询
            return true;
        }


        //1、反射拿到方法上的注解
        Method method = ((HandlerMethod) handler).getMethod();
            //判断该方法上面是否加了CheckRole
        boolean isAnno = method.isAnnotationPresent(CheckRole.class);

        if(isAnno){
            //加了进入到这

            //2、获取token
//            String token = request.getHeader("Authorization");
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)){
                Result<Object> result = Result.error(505, "未登录");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSON(result));
                return false;
            }
            //3、获取用户信息
            User User = loginService.checkToken(token);
            if (User==null){
                Result<Object> result = Result.error(505,"未登录");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSON(result));
                return false;
            }
            //4、获取注解中的具体值
            CheckRole annotation = method.getAnnotation(CheckRole.class);
            String[] role = annotation.role();
            List<String> annoRole = new ArrayList<>(Arrays.asList(role));//接口需要的权限

            //5、从数据库取当前用户的所有权限
            List<UserRole> user_id = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", User.getUserId()));
            List<String> roleIds = new ArrayList<>();
            for (UserRole userRole : user_id) {
                roleIds.add(userRole.getRoleId()+"");
            }
            List<Role> roles1 = roleService.list(new QueryWrapper<Role>().in("id", roleIds));
            List<String> dbRole = roles1.stream().map(Role::getFlag).collect(Collectors.toList());
            //6、比较接口需要的权限和用户所拥有的权限
            for (String s : dbRole) {
                for (String s1 : annoRole) {
                    if(StringUtils.equals(s,s1)){
                        UserDto userDto = new UserDto();
                        userDto.setUser(User);
                        userDto.setRoles(dbRole);
                        userLocal.set(userDto);
                        return true;
                    }
                }
            }
            //7、无权限
            Result<Object> result = Result.error(505,"无权限访问");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSON(result));
            return false;
        }

        return true;
    }


}
